const fs = require('fs');
const path = require('path');
const {
	sumSize,
	composeSize
} = require('../utils/index.js')

function traversal (dir = __dirname, fileCount = []) {
	try {
		const state = fs.statSync(dir);
		if (state.isDirectory()) {
			const dirs = fs.readdirSync(dir)
			for (const iterator of dirs) {
				traversal(path.join(dir, iterator), fileCount)
			}
		} else {
			fileCount.push(state.size)
		}
		return fileCount
	} catch (error) {
		throw error
	}
}

function computedSize (dir, plain) {
	return new Promise((resolve, reject) => {
		try {
			const listSize = traversal(dir, []);
			const fileSize = listSize.reduce(sumSize, 0);
			plain ? resolve(fileSize) : resolve(composeSize(fileSize))
		} catch (error) {
			reject(error)
		}
	})
}

module.exports = computedSize;